package com.recycle.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.recycle.common.Counts;
import com.recycle.common.ServerResponse;
import com.recycle.dao.UserInfoMapper;
import com.recycle.exception.BusinessException;
import com.recycle.exception.BusinessExceptionEnum;
import com.recycle.pojo.UserInfo;
import com.recycle.req.UserReq;
import com.recycle.res.Jscode2sessionReq;
import com.recycle.res.UserResp;
import com.recycle.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;

//用户相关
@Service
public class UserService {
    @Autowired
    UserInfoMapper userInfoMapper;
    private String key=null;
    public ServerResponse<UserResp> login(UserReq userReq){
    //用户不存在，则注册
    String openId = this.getSessionKeyOropenid(userReq.getCode());

    String decryptedData  = WechatUtils.decrypt(userReq.getEncryptedData(),this.key,userReq.getIv(),"utf-8");

        UserInfo user =   userInfoMapper.selectOpenIdUser(openId);

        UserResp p =  JsonUtil.string2Obj(decryptedData,UserResp.class);

        //不存在用户则进行注册
    if(ObjectUtil.isNull(user)){
        UserInfo info = new UserInfo();
        info.setPoints(10);
        if(ObjectUtil.isNotNull(p)&&ObjectUtil.isNotNull(p.getPhoneNumber())){
            String token = JwtUtil.createToken(openId);
            info.setPhoneNumber(p.getPhoneNumber());
            info.setOpenId(openId);
            int row = userInfoMapper.insertSelective(info);
            if(row>0){
                p.setToken(token);
                p.setOpenId(info.getOpenId());
                p.setCode(userReq.getCode());
                p.setId(info.getId());
                p.setEncryptedData(userReq.getEncryptedData());
                return ServerResponse.SuccessModel(p);
            }
        }else{
            throw  new BusinessException(BusinessExceptionEnum.NOTUSER);
        }

    }else{
        Date d = new Date();
     userInfoMapper.updateByOpenIdUser(d,openId);
      UserInfo info = userInfoMapper.selectOpenIdUser(openId);

        UserResp userResp = BeanUtil.copyProperties(info,UserResp.class);
        if(ObjectUtil.isNull(info)){
          throw  new BusinessException(BusinessExceptionEnum.NOTUSER);
      }
      if(ObjectUtil.isNotNull(info)){
          String token = JwtUtil.createToken(openId);
          userResp.setToken(token);
          userResp.setCode(userReq.getCode());
          userResp.setEncryptedData(userReq.getEncryptedData());
          userResp.setIv(userReq.getIv());
          return ServerResponse.SuccessModel(userResp);
      }
    }
    return ServerResponse.SuccessModel();
    }
    private String getSessionKeyOropenid(String code){
        try {
            StringBuilder stringBuilder = new StringBuilder(PropertiesUtil.getProperty("xcx.jscode2session"));
            stringBuilder.append("?appid="+ Counts.APPID);
            stringBuilder.append("&secret="+Counts.SECRET);
            stringBuilder.append("&js_code="+code);
            stringBuilder.append("&grant_type=authorization_code");
            String postResponse = HttpUtils.sendPostRequest(stringBuilder.toString(),null);
          Jscode2sessionReq jscode2sessionReq  =  JsonUtil.string2Obj(postResponse,Jscode2sessionReq.class);

          this.key = jscode2sessionReq.getSession_key();
          if(ObjectUtil.isNotEmpty(jscode2sessionReq.getErrcode())) {
              if (jscode2sessionReq.getErrcode() == BusinessExceptionEnum.CODE_INVALID.getCode()) {
                  throw new BusinessException(BusinessExceptionEnum.CODE_INVALID);
              } else if (jscode2sessionReq.getErrcode() == BusinessExceptionEnum.XCX_API_FREQUENNtLY.getCode()) {
                  throw new BusinessException(BusinessExceptionEnum.XCX_API_FREQUENNtLY);
              } else if (jscode2sessionReq.getErrcode() == BusinessExceptionEnum.CODE_BLOCKED.getCode()) {
                  throw new BusinessException(BusinessExceptionEnum.CODE_BLOCKED);
              } else if (jscode2sessionReq.getErrcode() == BusinessExceptionEnum.XCX_SYSTEM_ERROR.getCode()) {
                  throw new BusinessException(BusinessExceptionEnum.XCX_SYSTEM_ERROR);
              }
          }
          return jscode2sessionReq.getOpenid();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
